package com.jltx.xq.simplewatch.base;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.jltx.xq.simplewatch.base.presenter.BasePresenter;
import com.jltx.xq.simplewatch.utils.LifecycleInstrumentation;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import cn.jltx.support.SupportAppCompatActivity;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2017/08/18.
 */

public abstract class BaseAppCompatActivity<T extends BasePresenter> extends SupportAppCompatActivity implements BaseAppCompatApp{
    public T presenter;

    @Override
    final protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化Presenter
        presenter = initPresenter();
        //子类不再需要设置布局ID，也不再需要使用ButterKnife.bind()
        setContentView(provideContentViewId());
        ButterKnife.bind(this);
        initView(savedInstanceState);
        LifecycleInstrumentation.registerFragmentLifecycleCallbacks(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(presenter != null && !presenter.isViewAttached()){
            presenter.attachView(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(presenter != null){
            presenter.detachView();
        }
        LifecycleInstrumentation.unregisterFragmentLifecycleCallbacks(this);
    }

    @Override
    public void onExitFinish() {

    }

    /**
     * 判断是否已经将对应的subscribe订阅者订阅到了eventBus总线上
     * @param subscribe
     * @return
     */
    public boolean isEventBusRegisted(Object subscribe){
        return EventBus.getDefault().isRegistered(subscribe);
    }

    /**
     * 注册subscribe订阅事件到eventBus总线
     * @param subscribe
     */
    public void registerEventBus(Object subscribe){
        if(!isEventBusRegisted(subscribe)){
            EventBus.getDefault().register(subscribe);
        }
    }

    /**
     * 取消subscribe订阅事件
     * @param subscribe
     */
    public void unregisterEventBus(Object subscribe){
        if(isEventBusRegisted(subscribe)){
            EventBus.getDefault().unregister(subscribe);
        }
    }

    //得到当前界面的布局文件id(由子类实现)
    protected abstract int provideContentViewId();

    // 实例化presenter
    public abstract T initPresenter();

    public void initView(Bundle savedInstanceState) {

    }

}
